<?php

declare(strict_types=1);

namespace app\api\controller\User;

use app\BaseController;
use app\common\model\Config as ConfigModel;
use app\common\model\User\User as UserModel;
use app\common\model\Region as RegionModel;
use app\common\model\User\Pay as PayModel;
use app\common\model\User\Record as RecordModel;
use app\common\validate\User\Pay as PayValiDate;
use app\common\validate\User\User as UserValiDate;
use think\exception\Handle;
use think\facade\Session;

class Base extends BaseController
{
    // 注册
    public function register()
    {
        try {
            $params = $this->request->param();
            // 生成密码盐
            $salt = build_ranstr();
            // md5加密
            $password = md5($params['password'] . $salt);
            // 查询注册积分
            $point = ConfigModel::where(['key' => 'RegisterPoint'])->value('value');
            // 封装数据
            $data = [
                'email' => $params['email'],
                'password' => $password,
                'salt' => $salt,
                'point' => $point,
                'sex' => 0,
                'auth' => 0,
                'vip' => 1,
            ];
            // 验证数据 scene('register')=>场景验证
            validate(UserValiDate::class)->scene('register')->check($data);
            // 插入数据表
            $result = UserModel::create($data);
            if ($result == false) {
                throw new \Exception('注册失败');
            }
        } catch (\think\exception\ValidateException $e) {
            // 数据验证不通过时会进入，把错误信息显示
            $this->error($e->getMessage());
        } catch (\Exception $error) {
            $this->error($error->getMessage());
        }
        $this->success('注册成功');
    }
    // 登录
    public function login()
    {
        $params = $this->request->param();

        $User = UserModel::where('email', $params['email'])->find();

        if (!$User) {
            $this->error('用户不存在，请重新输入');
        }

        $password = md5($params['password'] . $User['salt']);

        if ($password != $User['password']) {
            $this->error('密码错误，请重新输入');
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region_text' => $User['region_text']
        ];

        $this->success('登录成功', null, $data);
    }
    // 登录验证
    public function check()
    {
        $userid = $this->request->param('userid');

        $User = UserModel::find($userid);

        if (!$User) {
            $this->error('非法登录');
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'wxAvatar_cdn' => $User['wxAvatar_cdn'],
            'wxAvatar' => $User['wxAvatar'],
            'wxNickname' => $User['wxNickname'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region_text' => $User['region_text']
        ];

        $this->success('验证成功', null, $data);
    }
    // 修改资料
    public function profile()
    {
        $params = $this->request->param();
        $User = UserModel::find($params['userid']);
        if (!$User) {
            $this->error('用户不存在');
        }
        $data = [
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content']
        ];
        // 提交的数据是否存在地区
        if (isset($params['code'])) {
            // 查询完整的地区代码
            $parentpath = RegionModel::where(['code' => $params['code']])->value('parentpath');
            // 判断地区是否存在
            if (!$parentpath) {
                $this->error('所选地区不存在');
            }
            // 切割
            [$province, $city, $district] = explode(',', $parentpath);
            $data['province'] = $province;
            $data['city'] = $city;
            // 追加到数组
            $data['district'] = $district;
        }
        // 提交的数据是否存在密码
        if (isset($params['password'])) {
            $salt = build_ranstr();

            $data['password'] = md5($params['password'] . $salt);

            $data['salt'] = $salt;
        }
        // 提交的数据是否存在头像
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size']) {
            // 调用上传操作
            $avatar = upload('avatar');
            // 判断上传是否成功
            if ($avatar['code'] === 0) {
                $this->error($avatar['msg']);
            }
            // 封装到数组
            $data['avatar'] = $avatar['data'];
        }
        // 提交的数据是否存在封面
        if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
            // 调用上传操作
            $cover = upload('cover');
            // 判断上传是否成功
            if ($cover['code'] === 0) {
                $this->error($cover['msg']);
            }
            // 封装到数组
            $data['cover'] = $cover['data'];
        }
        $result = UserModel::update($data, ['id' => $User['id']]);
        if ($result !== FALSE) {
            if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('./' . (string)$User['avatar']) && @unlink('./' . $User['avatar']);
            }

            if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('./' . (string)$User['cover']) && @unlink('./' . $User['cover']);
            }

            $user = UserModel::find($params['userid']);

            $UserData = [
                'id' => $user['id'],
                'email' => $user['email'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar_cdn'],
                'cover' => $user['cover_cdn'],
                'sex' => $user['sex'],
                'sex_text' => $user['sex_text'],
                'province' => $user['province'],
                'city' => $user['city'],
                'district' => $user['district'],
                'createtime' => $user['createtime'],
                'content' => $user['content'],
                'point' => $user['point'],
                'vip' => $user['vip'],
                'auth' => $user['auth'],
                'region_text' => $user['region_text']
            ];

            $this->success('更新成功', null, $UserData);
        } else {
            if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('./' . (string)$data['avatar']) && @unlink('./' . $data['avatar']);
            }

            if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('./' . (string)$data['cover']) && @unlink('./' . $data['cover']);
            }

            $this->error('更新失败');
        }
    }
    // 发送验证码
    public function email()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid');
            $User = UserModel::find($userid);
            if (!$User) {
                $this->error('User not found');
            }
            $salt = build_ranstr(4);

            Session::set("salt{$userid}", $salt);
            // 内容
            $msg = "帐号认证验证码为：$salt";

            $result = EmailSend($User['nickname'], $User['email'], $msg);

            if ($result === FALSE) {
                $this->error('验证码发送失败');
            } else {
                $this->success('验证码发送成功，请去邮箱查看验证码', null, $salt);
            }
        }
    }
    // 检查验证码
    public function emailcode()
    {
        $userid = $this->request->param('userid');
        $code = $this->request->param('code');
        $User = UserModel::find($userid);
        if (!$User) {
            $this->error('用户不存在');
        }
        $salt = Session::get("salt{$userid}");
        if ($salt != $code) {
            $this->error('验证码错误，请重新输入');
        }
        $User->auth = 1;
        // 保存
        $UserStatus = $User->save();
        // 判断是否成功
        if ($UserStatus === FALSE) {
            $this->error('验证失败');
        }
        $this->success('验证成功');
    }
    // 充值中心
    public function pay()
    {
        try {
            $userid = $this->request->param('userid');
            $point = $this->request->param('point');
            $content = $this->request->param('content');
            $User = UserModel::find($userid);
            if (!$User) {
                throw new \Exception('用户数据获取失败');
            };
            $data = [
                'userid' => $userid,
                'point' => $point,
                'status' => 0
            ];
            if (!empty($content)) {
                $data['content'] = $content;
            }
            validate(PayValiDate::class)->check($data);
            $result = PayModel::create($data);
            if ($result === false) {
                throw new \Exception('充值失败');
            }
        } catch (\think\exception\ValidateException $e) {
            $this->error($e->getMessage());
        } catch (\Exception $error) {
            $this->error($error->getMessage());
        }
        $this->success('充值成功,请等待审核');
    }
    // 充值记录
    public function payrecord()
    {
        $userid = $this->request->param('userid');
        $User = UserModel::find($userid);
        if (!$User) {
            $this->error('用户不存在');
        }
        $payrecord = PayModel::where(['userid' => $userid])->order('createtime', 'desc')->select();
        if ($payrecord === false) {
            $this->error('查询失败');
        }
        // halt($payrecord);
        $this->success('查询成功', null, $payrecord);
    }
    // 消费记录
    public function record()
    {
        $userid = $this->request->param('userid');
        $action = $this->request->param('action');
        $User = UserModel::find($userid);
        if (!$User) {
            $this->error('用户不存在');
        }
        if ($action=='uniapp') {
            $record = RecordModel::where(['userid' => $userid,'state'=>6])->select();
        }else{
            $record = RecordModel::where(['userid' => $userid,'state'=>5])->select();
        }
        if ($record === false) {
            $this->error('查询失败');
        }
        // halt($payrecord);
        $this->success('查询成功', null, $record);
    }
    // public function weixin()
    // {
    //     $code = $this->request->param('code');

    //     if (!$code) {
    //         return json(['code' => 0, 'msg' => '授权失败']);
    //     }

    //     $code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid=wxac4a7aa2c0e53e2e&secret=a978c71338d2289b2e3c3106caec1257&js_code={$code}&grant_type=authorization_code";

    //     $result = file_get_contents($code2Session);

    //     $data = json_decode($result, true);

    //     $openid = !empty($data['openid']) ? $data['openid'] : '';

    //     if (empty($openid)) {
    //         return json(['code' => 0, 'msg' => '获取临时登录凭证']);
    //     }

    //     $User = UserModel::where(['openid' => $openid])->find();

    //     if (!$User) {
    //         return json(['code' => 0, 'msg' => '请先绑定账号', 'url' => '/pages/news/news']);
    //     }

    //     return json(['code' => 1, 'msg' => '登录成功', 'data' => $result]);
    //     $data = [
    //         'id' => $User['id'],
    //         'email' => $User['email'],
    //         'nickname' => $User['nickname'],
    //         'avatar' => $User['avatar_cdn'],
    //         'cover' => $User['cover_cdn'],
    //         'sex' => $User['sex'],
    //         'sex_text' => $User['sex_text'],
    //         'province' => $User['province'],
    //         'city' => $User['city'],
    //         'district' => $User['district'],
    //         'createtime' => $User['createtime'],
    //         'content' => $User['content'],
    //         'point' => $User['point'],
    //         'vip' => $User['vip'],
    //         'auth' => $User['auth'],
    //         'region_text' => $User['region_text']
    //     ];

    //     return json(['code' => 1, 'msg' => '登录成功', 'data' => $data]);
    // }
    // public function bind()
    // {
    //     $params = $this->request->param();

    //     $User = UserModel::where(['email' => $params['email']])->find();

    //     if (!$params['code']) {
    //         return json(['code' => 0, 'msg' => '授权失败']);
    //     }

    //     $code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid=wxac4a7aa2c0e53e2e&secret=a978c71338d2289b2e3c3106caec1257&js_code={$params['code']}&grant_type=authorization_code";

    //     $result = file_get_contents($code2Session);

    //     $data = json_decode($result, true);

    //     $openid = !empty($data['openid']) ? $data['openid'] : '';

    //     if (empty($openid)) {
    //         return json(['code' => 0, 'msg' => '获取临时登录凭证']);
    //     }

    //     if ($User) {
    //         if (md5($params['password'] . $User['salt']) != $User['password']) {
    //             return json(['code' => 0, 'msg' => '密码错误']);
    //         }

    //         $result = UserMOdel::update(['openid' => $openid], ['id' => $User['id']]);

    //         if ($result !== FALSE) {
    //             $user = UserModel::find($User['id']);

    //             $data = [
    //                 'id' => $user['id'],
    //                 'email' => $user['email'],
    //                 'nickname' => $user['nickname'],
    //                 'avatar' => $user['avatar_cdn'],
    //                 'cover' => $user['cover_cdn'],
    //                 'sex' => $user['sex'],
    //                 'sex_text' => $user['sex_text'],
    //                 'province' => $user['province'],
    //                 'city' => $user['city'],
    //                 'district' => $user['district'],
    //                 'createtime' => $user['createtime'],
    //                 'content' => $user['content'],
    //                 'point' => $user['point'],
    //                 'vip' => $user['vip'],
    //                 'auth' => $user['auth'],
    //                 'region_text' => $user['region_text']
    //             ];

    //             return json(['code' => 1, 'msg' => '绑定成功', 'data' => $data]);
    //         } else {
    //             return json(['code' => 0, 'msg' => '绑定失败']);
    //         }
    //     }
    // }
}
